package org.apdplat.realtimelog.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apdplat.realtimelog.manager.RedisManager;
import org.apdplat.realtimelog.utils.TokenUtils;
import org.apdplat.realtimelog.web.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "AuthFilter")
public class AuthFilter implements Filter {

	// 提供给第三方的服务 与静态资源文件 及 登录相关方法
	private static final String[] EXCLUDE_URL = { "login", "/user/login", "loginOut", "css", "fonts", "images", "js", "lib" };

	@Autowired
	private RedisManager redisManager;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String scheme = request.getScheme();
		String serverName = request.getServerName();
		int port = request.getServerPort();
		String path = request.getContextPath();
		String basePath = scheme + "://" + serverName + ":" + port + path;
		String baseBodyPath = serverName + ":" + port + path;
		request.setAttribute("basePath", basePath);
		request.setAttribute("baseBodyPath", baseBodyPath);
		
		String uri = request.getRequestURI();
		if (filterUrl(uri)) {
			String loginToken = TokenUtils.getLoginToken(request);
			LoginUser loginUser = (LoginUser) redisManager.get(loginToken);
			if (null == loginUser) {
				HttpServletResponse response = (HttpServletResponse) servletResponse;
				response.sendRedirect(basePath + "/login");
				return;
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	private boolean filterUrl(String uri) {
		boolean flag = true;
		for (String u : EXCLUDE_URL) {
			if (uri.indexOf(u) > -1) {
				flag = false;
				break;
			}
		}
		return flag;
	}

	@Override
	public void destroy() {}
}